<script setup>
import dayjs from 'dayjs';

definePageMeta({
	layout: "flat",
})
const urlHome = useUrl();
console.log(urlHome.value);
const { params } = useRoute();
console.log("params:", params.nkv)
const mpp = useCookie('mpp');
const nkv = ref('');
if (nkv) {
	nkv.value = params.nkv
}
const isOpen = ref(false);
const strNkv = computed(() => nkv.value == '' ? "" : nkv.value)

const selectedDoc = ref(0);
const selectedTech = ref(0);
const selectedPol = ref(0);
const selectedLit = ref(0);
const selectedCadcam = ref(0);
const uslugiSelected = ref([]);

const uslInput = ref('');
const isUslInput = ref(false);
const uslInput1 = ref('');
const uslInput2 = ref('');
const colInput = ref('');
const col = ref(null);

const { data: oneNar, refresh: oneNarRefresh } = await useFetch(`${urlHome.value}lab/one_nar/`, {
	query: {
		naryad_nkv: strNkv,
	},
})

const { pending: pend, error, data: uslugiAll } = await useLazyFetch(urlHome.value + "lab/uslugi_all/")

async function addUsl() {
	if (colInput.value === '') {
		colInput.value = 1
	}
	const response = await $fetch(`${urlHome.value}lab/add_usl/`, {
		query: {
			naryad_nkv: params.nkv,
			kusl: uslInput1.value,
			kol: colInput.value,
			mpp: mpp.value,
		},
	})
	if (response.ok) {
		console.log(response.status);
		uslInput1.value = '';
		colInput.value = '';
		uslInput.value = '';
		isUslInput.value = false;
		refreshUslugi();
	} else {
		alert("Не удалось добавить")
	}
}

async function delUsl(usluga_id) {
	const response = await $fetch(`${urlHome.value}lab/delete_usl/`, {
		query: {
			usluga_id: usluga_id,
			mpp: mpp.value,
		},
	})
	if (response.ok) {
		console.log(response.status);
		uslInput1.value = '';
		colInput.value = '';
		isUslInput.value = false;
		refreshUslugi();
	} else {
		alert("Не удалось добавить")
	}
}

watch(oneNar, (newNar) => {
	console.log("watched")
	console.log("newNar: ", toRaw(newNar))
	selectedDoc.value = toRaw(newNar).naryad.sdl_set.doc;
	selectedTech.value = toRaw(newNar).naryad.sdl_set.tech;
	selectedPol.value = toRaw(newNar).naryad.sdl_set.pol;
	selectedLit.value = toRaw(newNar).naryad.sdl_set.lit;
	selectedCadcam.value = toRaw(newNar).naryad.sdl_set.cadcam;
})

const { data: imgList, refresh: imgListRefresh } = await useFetch(`${urlHome.value}lab/image_list/`, {
	watch: [oneNar],
	query: {
		naryad_nkv: strNkv,
	}
})

const { data: uslugi, refresh: refreshUslugi } = await useFetch(`${urlHome.value}lab/uslugi_by_nkv/`, {
	watch: [oneNar],
	query: {
		naryad_nkv: nkv,
	}
})

const { data: listDoc } = await useFetch(`${urlHome.value}lab/list_all_doc/`)

const { data: specList } = await useFetch(`${urlHome.value}lab/list_all_prof/`)

defineShortcuts({
	insert: {
		usingInput: true,
		handler: () => {
			isUslInput.value = true
		}
	}
})

const items = (row) => [
	[{
		label: 'Edit',
		icon: 'i-heroicons-pencil-square-20-solid',
		click: () => console.log('Edit', row.id)
	}, {
		label: 'Duplicate',
		icon: 'i-heroicons-document-duplicate-20-solid'
	}], [{
		label: 'Archive',
		icon: 'i-heroicons-archive-box-20-solid'
	}, {
		label: 'Move',
		icon: 'i-heroicons-arrow-right-circle-20-solid'
	}], [{
		label: 'Delete',
		icon: 'i-heroicons-trash-20-solid'
	}]
]

const columns = [{
	key: 'kusl',
	label: 'Код'
}, {
	key: 'nusl',
	label: 'Название услуги'
}, {
	key: 'kol',
	label: 'Кол-во'
}, {
	key: 'uet',
	label: 'УЕТ'
}, {
	key: 'price',
	label: 'Цена'
}, {
	key: 'stu',
	label: 'Сумма'
}, {
	key: 'actions'
}]

const sumUsl = computed(() => uslugi.value.reduce((accumulator, currentValue) => accumulator + Number(currentValue.stu), 0))

const sumMinus = computed(() => oneNar?.value?.naryad?.stu - sumUsl.value)

</script>

<template>
	<div>
		<h1></h1>
		<br>
		<NaryadListWork>
			<NuxtLink to="/menu">
				<UButton>Меню</UButton>
			</NuxtLink>
		</NaryadListWork>
		<UInput v-model.number="nkv" @keyup.enter="oneNarRefresh" class="max-w-xs" color="primary" variant="outline"
			placeholder="Введите номер наряда" />
		<br>
		<div>
			<div v-if="oneNar">
				<div class="px-2 grid lg:grod-cols-2 md:grid-cols-2 sm:grid-cols-1">
					<div class="form-label">Пациент: <b>{{ oneNar?.naryad?.patient?.fam }} {{
						oneNar?.naryad?.patient?.im }}
							{{ oneNar?.naryad?.patient?.ot }}</b></div>
					<div class="form-label">Дата рождения: <b>{{ oneNar?.naryad?.patient?.dr ?
						dayjs(oneNar?.naryad?.patient.dr).format('DD.MM.YYYY') : "" }}</b></div>
					<div class="form-label">Дата наряда: <b>{{ oneNar?.naryad?.dou ?
						dayjs(oneNar?.naryad?.dou).format('DD.MM.YYYY') : "" }}</b></div>
					<div class="form-label">Оплата: <b>{{ oneNar?.naryad?.opl?.name_opl }}</b></div>
					<div class="form-label">Номер квитанции: <b>{{ oneNar?.naryad?.nkv }}</b></div>
					<div class="form-label">Стоимость: <b>{{ oneNar?.naryad?.stu ?
						(oneNar?.naryad?.stu).toLocaleString() :
						""
							}} р.</b></div>
					<div class="form-label">Врач: <b> {{ oneNar?.naryad?.naryad_doc?.user ?
						`${oneNar?.naryad?.naryad_doc?.user?.fam} ${oneNar?.naryad?.naryad_doc?.user?.im}
							${oneNar?.naryad?.naryad_doc?.user?.ot}` : "" }}
						</b>
					</div>
					<div v-if="oneNar?.naryad?.id_etap > 1" class="form-label">
						Контейнер: <b>{{ oneNar?.naryad?.container?.id }}</b>
					</div>
				</div>
			</div>
			<br>
			<UInput color="green" type="file" accept="image/*" @change="handleFileSelection($event)"
				class="px-2 file-input w-full md:max-w-xs lg:max-w-xs xs:max-w-lg" />
			<br>
			<div class="px-2 grid grid-cols-4 gap-2 md:grid-cols-5 lg:grid-cols-5" v-auto-animate>
				<div v-for="image in imgList" :key="image">
					<img :src="urlCutHome + image" @click="openModalImage(image)" alt="image"
						class="w-16 md:w-24 lg:w-28">
				</div>
			</div>
			<br>
			<div class="flex flex-row">
				<div class="sm:grid grid-cols-5 gap-2">
					<div class="form-control w-full md:max-w-xs lg:max-w-sm xs:max-w-lg">
						<label class="label">
							<span class="label-text ">Врач</span>
						</label>
					</div>
					<div class="form-control w-full md:max-w-xs lg:max-w-sm xs:max-w-lg">
						<label class="label">
							<span class="label-text ">Техник</span>
						</label>
						<USelect v-model="selectedTech" color="primary" variant="outline" :options="specList.list_tech"
							option-attribute="name" value-attribute="mpp" />
					</div>
					<div class="form-control w-full md:max-w-xs lg:max-w-sm xs:max-w-lg">
						<label class="label">
							<span class="label-text">Полировщик</span>
						</label>
						<USelect v-model="selectedPol" color="primary" variant="outline" :options="specList.list_pol"
							option-attribute="name" value-attribute="mpp" />
					</div>

					<div class="form-control w-full md:max-w-xs lg:max-w-sm xs:max-w-lg">
						<label class="label">
							<span class="label-text">Литейщик</span>
						</label>
						<USelect v-model="selectedLit" color="primary" variant="outline" :options="specList.list_lit"
							option-attribute="name" value-attribute="mpp" />
					</div>

					<div class="form-control w-full md:max-w-xs lg:max-w-sm xs:max-w-lg">
						<label class="label">
							<span class="label-text">CAD/CAM</span>
						</label>
						<USelect ref="col" v-model="selectedCadcam" color="primary" variant="outline"
							:options="specList.list_cadcam" option-attribute="name" value-attribute="mpp" />
					</div>
				</div>
			</div>
			<div class="text-lg">
				<div>
					<div class="font-bold">
						Услуги
					</div>
					<div>
						<UButton color="primary" label="Добавить услуг" v-on:click="isUslInput = true" />
					</div>
					<div>
						<div>Сумма услуг <b>{{ sumUsl }}руб.</b> <i>(для проверки)</i></div>
					</div>
					<div>
						<div>Разница сумм <b>{{ sumMinus }}руб.</b> <i>(для проверки)</i></div>
					</div>
					<div>
						<UTable :rows="uslugi" :columns="columns">
							<template #kusl-data="{ row }">
								<span>{{ row.kusl }}</span>
							</template>
							<template #actions-data="{ row }">
								<UButton color="gray" @click="delUsl(row.id)" icon="i-heroicons-trash-20-solid" />
							</template>
						</UTable>
					</div>
				</div>
			</div>
		</div>
		<UModal v-model="isUslInput">
			<div class="p-4 pb-48">
				<div>
					Введите код услуги
					<UInput color="primary" v-model="uslInput1" @keyup.enter="addUsl" />
				</div>
				<div>
					Введите кол-во
					<UInput color="primary" v-model="colInput" @keyup.enter="addUsl" />
				</div>
				<div class="pt-4">
					<UButton @click="addUsl">Добавить</UButton>
				</div>
			</div>
		</UModal>
	</div>
</template>